import os
import markdown
import time
import sys
from jinja2 import Environment, PackageLoader, FileSystemLoader, select_autoescape

# 1. 直接用变量定义输出目录（替代原 Flask 的 app.config）
OUTPUT_FOLDER = './data'
# 确保输出文件夹存在
os.makedirs(OUTPUT_FOLDER, exist_ok=True)


def _get_jinja_env():
    """保持原有的 Jinja2 模板加载逻辑，无改动"""
    try:
        return Environment(loader=PackageLoader('app', 'static'),
                           autoescape=select_autoescape(['html', 'xml']))
    except Exception:
        static_dir = os.path.join(os.path.dirname(__file__), 'static')
        return Environment(loader=FileSystemLoader(static_dir),
                           autoescape=select_autoescape(['html', 'xml']))


def render_markdown_file(md_path: str) -> str:
    """保持原有的 Markdown 转 HTML 核心逻辑，无改动"""
    if not os.path.exists(md_path):
        raise FileNotFoundError(md_path)
    with open(md_path, 'r', encoding='utf-8') as rf:
        content = rf.read()
    # 原有扩展配置保留（根据你的实际需求调整）
    extensions = [
        "tables", "app.extensions.checkbox", "app.extensions.radio",
        "app.extensions.textbox"
    ]
    html = markdown.markdown(content,
                             extensions=extensions,
                             output_format="html5")
    env = _get_jinja_env()
    javascript = env.get_template('app.js').render()
    test_html = env.get_template('base.html').render(content=html,
                                                     javascript=javascript)
    test_html = env.get_template('wrapper.html').render(content=test_html)
    base_name = os.path.splitext(os.path.basename(md_path))[0]
    filename = f"{base_name}_{int(time.time())}.html"
    out_path = os.path.join(OUTPUT_FOLDER, filename)
    with open(out_path, 'w', encoding='utf-8') as wf:
        wf.write(test_html)
    return out_path


if __name__ == '__main__':
    # 保持原有的命令行逻辑，无改动
    if len(sys.argv) > 1:
        md_path = sys.argv[1]
        try:
            out = render_markdown_file(md_path)
            print(f"生成完成：{out}")
        except Exception as e:
            print("生成失败：", e)
        sys.exit(0)
    # 移除原 Flask 启动服务器的代码（因为你不需要）
    else:
        print("请传入 Markdown 文件路径，格式：python main.py 你的MD文件路径")